//
//  WYZ_LogInViewController.m
//  WYZ_YoungChat
//
//  Created by dllo on 16/3/11.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "WYZ_LogInViewController.h"

#import "WYZ_RegistrationViewController.h"

@interface WYZ_LogInViewController ()<UITextFieldDelegate>
@property(nonatomic,retain)UITextField  *account;//账号
@property(nonatomic,retain)UITextField *secretText;//密码

@end

@implementation WYZ_LogInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithWhite:0.789 alpha:0.2 ];
    
    
    
    [self createView];
    
    
}
-(void)createView{
    
    UIImageView  *headImageView =[[UIImageView alloc] init];
    [self.view addSubview:headImageView];
    headImageView.backgroundColor = [UIColor clearColor];
    headImageView.layer.borderColor =[[UIColor orangeColor]CGColor];
    headImageView.layer.cornerRadius = 45;
    headImageView.layer.masksToBounds = YES;
    [headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(70 * WIDTH);
        make.left.mas_equalTo(160 * WIDTH);
        make.height.mas_equalTo(90 * WIDTH);
        make.width.mas_equalTo(90 *WIDTH);
    }];
    
    
    self.account = [[UITextField alloc] init];
    self.account.placeholder = @"手机号/账号";
    self.account.clearButtonMode = UITextFieldViewModeAlways;
    self.account.textAlignment =1;
    self.account.layer.borderColor =[[UIColor colorWithWhite:0.897 alpha:1.000]CGColor];
    NSString *username = [self lastLoginUsername];
    if (username && username.length > 0) {
        _account.text = username;
    }

    self.account.layer.borderWidth = 1;
    self.account.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:self.account];
    [self.account becomeFirstResponder];
    [self.account mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headImageView.mas_bottom).offset(20);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(70 * HEIGHT);
    }];
    
    self.secretText = [[UITextField alloc] init];
    self.secretText .placeholder = @"密码";
    self.secretText.secureTextEntry = YES;
    self.secretText .clearButtonMode = UITextFieldViewModeAlways;
    self.secretText .textAlignment =1;
    self.secretText.layer.borderColor =[[UIColor colorWithWhite:0.897 alpha:1.000]CGColor];
    self.secretText.layer.borderWidth = 1;
    self.secretText .backgroundColor =[UIColor whiteColor];
    [self.view addSubview:self.secretText ];
    [self.secretText  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.account.mas_bottom).offset(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(70 * HEIGHT);
    }];
    
    
    UIButton *ashoreButton =[UIButton buttonWithType:UIButtonTypeSystem];
    ashoreButton.backgroundColor =[UIColor orangeColor];
    ashoreButton.layer.cornerRadius =5;
    [self.view addSubview:ashoreButton];
    [ashoreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    ashoreButton.titleLabel.font =[UIFont systemFontOfSize:20];
    [ashoreButton setTitle:@"登陆" forState:UIControlStateNormal];
    [ashoreButton addTarget:self action:@selector(ashoreButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [@[ashoreButton]  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.secretText.mas_bottom).offset(20);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(50);
    }];
    
    
    UIButton *bottomButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:bottomButton];
    bottomButton.titleLabel.font =[UIFont systemFontOfSize:20];
    [bottomButton setTintColor:[UIColor orangeColor]];
    [bottomButton setTitle:@"新用户" forState:UIControlStateNormal];
    [bottomButton addTarget:self action:@selector(bottomButton:) forControlEvents:UIControlEventTouchUpInside];
    [@[bottomButton]  mas_makeConstraints:^(MASConstraintMaker *make) {
        //       mask.top.mas_equalTo(ashoreButton.mas_bottom).offset()
        make.bottom.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(100 * WIDTH);
        make.height.mas_equalTo(50 * HEIGHT);
    }];
    
    
}
#pragma mark 登陆按钮
-(void)ashoreButton:(UIButton *)ashoreButton
{
    if (![self isEmpty]) {
        [self.view endEditing:YES];
        //支持是否为中文
        if ([self.account.text isChinese]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"login.nameNotSupportZh", @"Name does not support Chinese")
                                  message:nil
                                  delegate:nil
                                  cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                  otherButtonTitles:nil];
            
            [alert show];
            
            return;
        }
        /*
         #if !TARGET_IPHONE_SIMULATOR
         //弹出提示
         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"login.inputApnsNickname", @"Please enter nickname for apns") delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"Cancel") otherButtonTitles:NSLocalizedString(@"ok", @"OK"), nil];
         [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
         UITextField *nameTextField = [alert textFieldAtIndex:0];
         nameTextField.text = self.usernameTextField.text;
         [alert show];
         #elif TARGET_IPHONE_SIMULATOR
         [self loginWithUsername:_usernameTextField.text password:_passwordTextField.text];
         #endif
         */
        [self loginWithUsername:_account.text password:_secretText.text];
    }
    
}



//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    [self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
    //异步登陆账号
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:username
                                                        password:password
                                                      completion:
     ^(NSDictionary *loginInfo, EMError *error) {
         [self hideHud];
         if (loginInfo && !error) {
             //设置是否自动登录
             [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
             
             //获取数据库中数据
             [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
             
             //获取群组列表
             [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
             
             //发送自动登陆状态通知
             [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
             
             //保存最近一次登录用户名
             [self saveLastLoginUsername];
         }
         else
         {
             switch (error.errorCode)
             {
                 case EMErrorNotFound:
                     TTAlertNoTitle(error.description);
                     break;
                 case EMErrorNetworkNotConnected:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                     break;
                 case EMErrorServerNotReachable:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                     break;
                 case EMErrorServerAuthenticationFailure:
                     TTAlertNoTitle(error.description);
                     break;
                 case EMErrorServerTimeout:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                     break;
                 default:
                     TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
                     break;
             }
         }
     } onQueue:nil];
}
//弹出提示的代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView cancelButtonIndex] != buttonIndex) {
        //获取文本输入框
        UITextField *nameTextField = [alertView textFieldAtIndex:0];
        if(nameTextField.text.length > 0)
        {
            //设置推送设置
            [[EaseMob sharedInstance].chatManager setApnsNickname:nameTextField.text];
        }
    }
    //登陆
    [self loginWithUsername:_account.text password:_secretText.text];
}


#pragma mark  申请账号
-(void)bottomButton:(UIButton *)bottomButton
{
    WYZ_RegistrationViewController *registrationVC = [[WYZ_RegistrationViewController alloc] init];
    [self presentViewController:registrationVC animated:YES completion:^{
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.account resignFirstResponder];
    [self.secretText resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (textField == self.account)
    {
        [self.account resignFirstResponder];
        [self.secretText becomeFirstResponder];
        return YES;
    }else
    {
        [self.secretText resignFirstResponder];
        return YES;
    }
    
}


#pragma mark 判断用户名密码是否为空
- (BOOL)isEmpty{
    BOOL ret = NO;
    NSString *username = _account.text;
    NSString *password = _secretText.text;
    if (username.length == 0 || password.length == 0) {
        ret = YES;
    }
    return ret;
}
#pragma  mark - private
- (void)saveLastLoginUsername
{
    NSString *username = [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:kSDKUsername];
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
        [ud synchronize];
    }
}

- (NSString*)lastLoginUsername
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *username = [ud objectForKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
    if (username && username.length > 0) {
        return username;
    }
    return nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
@end
